package com.example.attrimirror.ui.attribute;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.attrimirror.databinding.FragmentAttributeBinding;
import com.example.attrimirror.model.Attribute;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class AttributeFragment extends Fragment implements AttributeAdapter.OnAttributeUpdateListener {

    private FragmentAttributeBinding binding;
    private AttributeAdapter adapter;
    private List<Attribute> allAttributes;
    private boolean showingProgress = true;
    private Handler updateHandler = new Handler();
    private final static long UPDATE_INTERVAL = 30000; // 30秒更新一次
    private File attributeFile;
    private Gson gson = new Gson();

    private final Runnable updateRunnable = new Runnable() {
        @Override
        public void run() {
            updateAttributeList();
            updateHandler.postDelayed(this, UPDATE_INTERVAL);
        }
    };

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                            ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentAttributeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 初始化文件路径
        File dataDir = new File(Environment.getExternalStorageDirectory(), "AttriMirror/data");
        attributeFile = new File(dataDir, "attribute.json");

        // 设置RecyclerView
        RecyclerView recyclerView = binding.recyclerView;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new AttributeAdapter(this);  // 传入this作为监听器
        recyclerView.setAdapter(adapter);

        // 设置SwipeRefreshLayout
        binding.swipeRefresh.setOnRefreshListener(() -> {
            updateAttributeList();
            binding.swipeRefresh.setRefreshing(false);
        });

        // 加载所有属性
        loadAttributes();

        // 设置标签点击事件
        binding.btnProgress.setOnClickListener(v -> {
            showingProgress = true;
            updateAttributeList();
            updateTabStyle();
        });

        binding.btnHindrance.setOnClickListener(v -> {
            showingProgress = false;
            updateAttributeList();
            updateTabStyle();
        });

        // 初始化标签样式
        updateTabStyle();

        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        updateHandler.post(updateRunnable);
    }

    @Override
    public void onPause() {
        super.onPause();
        updateHandler.removeCallbacks(updateRunnable);
    }

    private void loadAttributes() {
        // 从文件加载属性列表
        File dataDir = new File(Environment.getExternalStorageDirectory(), "AttriMirror/data");
        File attributeFile = new File(dataDir, "attribute.json");
        
        try {
            if (attributeFile.exists()) {
                Gson gson = new Gson();
                Type type = new TypeToken<List<Attribute>>(){}.getType();
                try (FileReader reader = new FileReader(attributeFile)) {
                    allAttributes = gson.fromJson(reader, type);
                    updateAttributeList();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "加载属性数据失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void updateAttributeList() {
        if (allAttributes != null) {
            List<Attribute> filteredAttributes = allAttributes.stream()
                .filter(attr -> attr.isPositive() == showingProgress)
                .collect(Collectors.toList());
            adapter.submitList(filteredAttributes);
        }
    }

    private void updateTabStyle() {
        binding.btnProgress.setEnabled(!showingProgress);
        binding.btnHindrance.setEnabled(showingProgress);
        // 可以添加更多样式变化，比如改变背景色等
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void onAttributeUpdated(Attribute attribute) {
        // 更新内存中的属性列表
        if (allAttributes != null) {
            for (int i = 0; i < allAttributes.size(); i++) {
                if (allAttributes.get(i).getId().equals(attribute.getId())) {
                    allAttributes.set(i, attribute);
                    break;
                }
            }
            
            // 保存到文件
            saveAttributes();
        }
    }

    private void saveAttributes() {
        try {
            if (attributeFile != null && allAttributes != null) {
                try (FileWriter writer = new FileWriter(attributeFile)) {
                    gson.toJson(allAttributes, writer);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "保存属性数据失败", Toast.LENGTH_SHORT).show();
        }
    }
} 